const Router = require('@koa/router');
const { Article, User } = require('../databases');
const { Op } = require('sequelize');

const articleRouter = new Router({
    prefix: '/article'
});

// 获取文章列表
articleRouter.get('/', async (ctx) => {
    try {
        const { 
            page = 1, 
            pageSize = 10, 
            status,
            authorId,
            search,
            categories 
        } = ctx.query;
        const offset = (page - 1) * pageSize;
        
        // 查询条件
        const where = {};
        if (status) {
            where.status = status;
        }
        if (authorId) {
            where.authorId = authorId;
        }
        if (search) {
            where[Op.or] = [
                { title: { [Op.like]: `%${search}%` } },
                { content: { [Op.like]: `%${search}%` } }
            ];
        }
        if (categories) {
            // 由于categories存储为JSON字符串，需要模糊匹配
            const categoryList = Array.isArray(categories) ? categories : [categories];
            where[Op.and] = categoryList.map(category => ({
                categories: { [Op.like]: `%${category}%` }
            }));
        }

        const { count, rows } = await Article.findAndCountAll({
            where,
            offset,
            limit: parseInt(pageSize),
            order: [['createdAt', 'DESC']],
            include: [{
                model: User,
                attributes: ['username'], // 只获取用户名
                as: 'author'
            }]
            // 移除排除content字段的配置，使其返回content字段
        });

        ctx.body = {
            status: 'success',
            data: {
                total: count,
                items: rows,
                currentPage: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 获取单个文章详情
articleRouter.get('/:id', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        ctx.body = {
            status: 'success',
            data: article
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 创建新文章
articleRouter.post('/', async (ctx) => {
    try {
        console.log('Creating article, request body:', ctx.request.body);
        // 创建文章时排除articleId字段，让数据库自动生成
        const { articleId, ...articleData } = ctx.request.body;
        
        // 验证必要字段
        const requiredFields = ['title', 'content', 'authorId'];
        for (const field of requiredFields) {
            if (!articleData[field]) {
                ctx.status = 400;
                ctx.body = {
                    status: 'error',
                    message: `缺少必要字段: ${field}`
                };
                return;
            }
        }

        // 处理分类数据
        if (articleData.categories && !Array.isArray(articleData.categories)) {
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '分类必须是数组格式'
            };
            return;
        }

        console.log('Creating article with data:', articleData);
        const article = await Article.create(articleData);
        console.log('Article created successfully:', article.toJSON());
        ctx.status = 201;
        ctx.body = {
            status: 'success',
            data: article
        };
    } catch (error) {
        console.error('Error creating article:', error);
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message || '创建文章失败'
        };
    }
});

// 更新文章
articleRouter.put('/:id', async (ctx) => {
    try {
        console.log('Update article request received, id:', ctx.params.id);
        console.log('Request body:', ctx.request.body);
        
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            console.log('Article not found, id:', ctx.params.id);
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        // 处理分类数据
        const updates = ctx.request.body;
        console.log('Updates to apply:', updates);
        
        // 验证必要字段
        const requiredFields = ['title', 'content', 'authorId'];
        for (const field of requiredFields) {
            if (updates[field] === undefined || updates[field] === null || updates[field] === '') {
                console.log('Missing required field:', field);
                ctx.status = 400;
                ctx.body = {
                    status: 'error',
                    message: `缺少必要字段: ${field}`
                };
                return;
            }
        }

        if (updates.categories && !Array.isArray(updates.categories)) {
            console.log('Invalid categories format, should be array');
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '分类必须是数组格式'
            };
            return;
        }

        await article.update(updates);
        console.log('Article updated successfully, id:', ctx.params.id);
        ctx.body = {
            status: 'success',
            data: article
        };
    } catch (error) {
        console.error('Update article error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message || '服务器内部错误'
        };
    }
});

// 删除文章
articleRouter.delete('/:id', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        await article.destroy();
        ctx.body = {
            status: 'success',
            message: '文章已删除'
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 更新文章状态
articleRouter.patch('/:id/status', async (ctx) => {
    try {
        const { status } = ctx.request.body;
        if (!['draft', 'pending', 'published'].includes(status)) {
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '无效的文章状态'
            };
            return;
        }

        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        await article.update({ status });
        ctx.body = {
            status: 'success',
            data: article
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 获取热门文章
// articleRouter.get('/popular/list', async (ctx) => {
//     try {
//         const { limit = 10 } = ctx.query;
//         const articles = await Article.findPopular(parseInt(limit));
        
//         ctx.body = {
//             status: 'success',
//             data: articles
//         };
//     } catch (error) {
//         ctx.status = 500;
//         ctx.body = {
//             status: 'error',
//             message: error.message
//         };
//     }
// });

// 获取作者的文章列表
articleRouter.get('/author/:authorId', async (ctx) => {
    try {
        const articles = await Article.findByAuthor(ctx.params.authorId);
        
        ctx.body = {
            status: 'success',
            data: articles
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 点赞文章
articleRouter.post('/:id/like', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        await article.increment('likeCount');
        await article.reload();
        
        ctx.body = {
            status: 'success',
            data: { likeCount: article.likeCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 收藏文章
articleRouter.post('/:id/favorite', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        await article.increment('favoriteCount');
        await article.reload();
        
        ctx.body = {
            status: 'success',
            data: { favoriteCount: article.favoriteCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 取消点赞文章
articleRouter.delete('/:id/like', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        if (article.likeCount > 0) {
            await article.decrement('likeCount');
            await article.reload();
        }
        
        ctx.body = {
            status: 'success',
            data: { likeCount: article.likeCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

// 取消收藏文章
articleRouter.delete('/:id/favorite', async (ctx) => {
    try {
        const article = await Article.findByPk(ctx.params.id);
        if (!article) {
            ctx.status = 404;
            ctx.body = {
                status: 'error',
                message: '文章不存在'
            };
            return;
        }

        if (article.favoriteCount > 0) {
            await article.decrement('favoriteCount');
            await article.reload();
        }
        
        ctx.body = {
            status: 'success',
            data: { favoriteCount: article.favoriteCount }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});

//获取文章总数
articleRouter.get('/total/articles', async (ctx) => {
    try {
        const total = await Article.count();
        ctx.body = {
            status: 'success',
            data: { total }
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: error.message
        };
    }
});


module.exports = articleRouter;